package cn.zwk.drawing.infrastructure.configuration;

import cn.zwk.drawing.domain.configuration.model.SystemConfiguration;
import cn.zwk.drawing.domain.configuration.service.ConfigurationDomainService;
import cn.zwk.drawing.domain.diagram.model.DiagramDefinition;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheEvict;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.time.LocalDateTime;

/**
 * 配置管理服务实现
 */
@Slf4j
@Service
public class ConfigurationService implements ConfigurationDomainService {
    
    // 内存配置存储（生产环境可替换为数据库）
    private final Map<String, SystemConfiguration> configurationStore = new ConcurrentHashMap<>();
    
    @Override
    @Cacheable(value = "configuration", key = "#configId")
    public Optional<SystemConfiguration> getConfiguration(String configId) {
        log.debug("获取配置: {}", configId);
        return Optional.ofNullable(configurationStore.get(configId));
    }
    
    @Override
    public List<SystemConfiguration> getConfigurationsByType(SystemConfiguration.ConfigurationType type) {
        return configurationStore.values().stream()
                .filter(config -> type.equals(config.getType()))
                .filter(config -> Boolean.TRUE.equals(config.getEnabled()))
                .toList();
    }
    
    @Override
    @CacheEvict(value = "configuration", key = "#configuration.configId")
    public SystemConfiguration saveConfiguration(SystemConfiguration configuration) {
        if (configuration.getConfigId() == null) {
            configuration.setConfigId(UUID.randomUUID().toString());
        }
        
        if (configuration.getCreatedAt() == null) {
            configuration.setCreatedAt(LocalDateTime.now());
        }
        configuration.setLastModified(LocalDateTime.now());
        
        if (configuration.getEnabled() == null) {
            configuration.setEnabled(true);
        }
        
        configurationStore.put(configuration.getConfigId(), configuration);
        log.info("保存配置: {} - {}", configuration.getConfigId(), configuration.getName());
        
        return configuration;
    }
    
    @Override
    @CacheEvict(value = "configuration", key = "#configId")
    public void deleteConfiguration(String configId) {
        configurationStore.remove(configId);
        log.info("删除配置: {}", configId);
    }
    
    @Override
    @CacheEvict(value = "configuration", allEntries = true)
    public void reloadConfigurations() {
        log.info("重载所有配置");
        // 这里可以从外部配置源重新加载
        initializeDefaultConfigurations();
    }
    
    @Override
    public Optional<DiagramDefinition> getDiagramConfiguration() {
        // 从配置中构建图表定义
        Optional<SystemConfiguration> diagramConfig = 
            getConfigurationsByType(SystemConfiguration.ConfigurationType.DIAGRAM)
                .stream()
                .findFirst();
                
        if (diagramConfig.isEmpty()) {
            return Optional.empty();
        }
        
        SystemConfiguration config = diagramConfig.get();
        return Optional.of(DiagramDefinition.builder()
                .diagramId("default")
                .name(config.getStringValue("name", "默认架构图"))
                .plantUmlContent(config.getStringValue("plantUmlContent", ""))
                .version(config.getVersion())
                .lastModified(config.getLastModified())
                .build());
    }
    
    @Override
    public boolean validateConfiguration(SystemConfiguration configuration) {
        if (configuration == null) return false;
        if (configuration.getName() == null || configuration.getName().trim().isEmpty()) return false;
        if (configuration.getType() == null) return false;
        if (configuration.getContent() == null) return false;
        
        return true;
    }
    
    @Override
    public List<SystemConfiguration> getConfigurationHistory(String configId) {
        // 简化实现，实际可以从审计表获取
        return List.of();
    }
    
    /**
     * 初始化默认配置
     */
    private void initializeDefaultConfigurations() {
        // 默认图表配置
        SystemConfiguration diagramConfig = SystemConfiguration.builder()
                .configId("default-diagram")
                .name("默认架构图配置")
                .type(SystemConfiguration.ConfigurationType.DIAGRAM)
                .content(Map.of(
                    "name", "系统架构图",
                    "plantUmlContent", getDefaultPlantUmlContent(),
                    "theme", "blueprint"
                ))
                .version("1.0")
                .enabled(true)
                .environment("default")
                .build();
        
        saveConfiguration(diagramConfig);
        
        // 默认性能配置
        SystemConfiguration perfConfig = SystemConfiguration.builder()
                .configId("default-performance")
                .name("性能配置")
                .type(SystemConfiguration.ConfigurationType.PERFORMANCE)
                .content(Map.of(
                    "renderTimeout", 30,
                    "scriptTimeout", 60,
                    "maxConcurrent", 10,
                    "cacheExpire", 300
                ))
                .version("1.0")
                .enabled(true)
                .environment("default")
                .build();
                
        saveConfiguration(perfConfig);
    }
    
    /**
     * 获取默认PlantUML内容
     */
    private String getDefaultPlantUmlContent() {
        return """
            @startuml architecture
            !theme blueprint
            
            node "API Gateway" as api #lightblue
            node "User Service" as user #lightgreen  
            node "Order Service" as order #lightyellow
            node "Database" as db #lightgray
            
            api --> user : HTTP
            api --> order : HTTP  
            user --> db : SQL
            order --> db : SQL
            
            @enduml
            """;
    }
}